package com.example.controller;

import com.example.domain.Student;
import com.example.service.StudentService;
import com.example.util.EasyuiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 学生信息前端面控制类
 */
@RestController
@RequestMapping(value = "/student")
@Slf4j
public class StudentController {
    @Autowired
    private StudentService studentService;
    
    /**
     * 查询所有学生,并分页
     *
     * @param page    页码,从1开始,后端从0开始
     * @param rows    每页的条数
     * @param sort    需要排序的列
     * @param order   排序的方向
     * @param clazzid 班级id,可以通过clazzid来获取这个班级的所有人
     * @return Easyui中datagrid的数据结构, row和data
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public EasyuiResult<Student> list(@RequestParam(name = "page", defaultValue = "1", required = false) int page,
                                      @RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
                                      @RequestParam(name = "sort", defaultValue = "id", required = false) String sort,
                                      @RequestParam(name = "order", defaultValue = "DESC", required = false) String order,
                                      @RequestParam(name = "clazzid", defaultValue = "0", required = false) int clazzid
    ) {
        log.info("StudentController 学生列表(/student/list),参数为 page={},row={},sort={},order={},clazzid={}",
                page - 1, rows, sort, order, clazzid);
        
        return studentService.list(Student.USER_STUDENT, page - 1, rows, sort, order, clazzid);
    }
    
    /**
     * 更新和保存学生.
     *
     * @param student 接收参数的实体.要注意,前端如果穿过的数据如果包含clazz(班级),其id要通过<strong>clazz.id</strong>的形式
     * @return 结果.success/error
     */
    @RequestMapping(value = {"/update", "add"}, method = RequestMethod.POST)
    public String update(Student student) {
        log.info("将要更新或者保存的student实体,student={}", student);
        final int result = studentService.update(student);
        if (result > 0) {
            return "success";
        } else {
            return "error";
        }
    }
    
    /**
     * 删除方法
     *
     * @param ids 学生id.前端穿过的是数据,注意接收的方式.<strong>@RequestParam(value = "ids[]")</strong>
     * @return 结果 success/error
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public String delete(@RequestParam(value = "ids[]") int[] ids) {
        log.info("将要删除student,ids={}", ids);
        studentService.delete(ids);
        return "success";
    }
}
